package cn.chiship.sdk.core.util.ip;

import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.exception.custom.BusinessException;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.core.util.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取地址类
 *
 * @author lijian
 */
public class AddressUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(AddressUtils.class);

    /**
     * IP地址查询
     * https://qifu-api.baidubce.com/ip/geo/v1/district?ip=144.255.6.48
     */
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    /**
     * 未知地址
     */
    public static final String UNKNOWN = "XX XX";

    private AddressUtils() {
    }

    public static String getRealAddressByIp(String ip) {
        String address = UNKNOWN;
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        try {
            Map<String, Object> queries = new HashMap<>(2);
            queries.put("ip", ip);
            queries.put("json", "true");

            BaseResult baseResult = HttpUtil.getInstance().doGet(IP_URL, queries);
            if (!baseResult.isSuccess()) {
                throw new BusinessException(baseResult.getMessage());
            }
            String respStr = StringUtil.getString(baseResult.getData());
            if (StringUtil.isNullOrEmpty(respStr)) {
                LOGGER.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
            JSONObject obj = JSON.parseObject(respStr);
            String region = obj.getString("pro");
            String city = obj.getString("city");
            String operator = obj.getString("addr").split(" ")[1];
            return String.format("%s %s %s", region, city, operator);
        } catch (Exception e) {
            LOGGER.error("获取地理位置异常 {}", ip);
        }
        return address;
    }
}
